#include "bittablemanager.h"

BitTableManager* BitTableManager::m_instance = NULL;

BitTableManager::BitTableManager()
{
}

BitTableManager::~BitTableManager()
{
}

BitTableManager* BitTableManager::instance()
{
    if (m_instance == NULL)
        m_instance = new BitTableManager();
    return m_instance;
}

BitHashTableHandle* BitTableManager::createDiskTableHandle(std::string path, std::string name)
{
    BitTableMap::iterator it = m_tables.find(name);
    if (it != m_tables.end())
        return it->second->getHashHandle();

    path = name + ".dat";
    DiskBitTable *table = new DiskBitTable(path.c_str());

    if (!table->init()) {
        delete table;
        return NULL;
    }

    m_tables[name] = table;

    return table->getHashHandle();
}

BitHashTableHandle* BitTableManager::createMemTableHandle(std::string name)
{
    BitTableMap::iterator it = m_tables.find(name);
    if (it != m_tables.end())
        return it->second->getHashHandle();

    MemBitTable *table = new MemBitTable();

    if (!table->init()) {
        delete table;
        return NULL;
    }

    m_tables[name] = table;

    return table->getHashHandle();
}

BitHashTableHandle* BitTableManager::getTableHandle(std::string name)
{
    BitTableMap::iterator it = m_tables.find(name);
    if (it != m_tables.end())
        return it->second->getHashHandle();
    return NULL;
}

void BitTableManager::destoryTableHandle(std::string name)
{
    BitTableMap::iterator it = m_tables.find(name);
    if (it != m_tables.end()) {
        BitTable *table = it->second;
        delete table;
        m_tables.erase(it);
    }
}

